using BlazorAdmin.Interface;
using BlazorAdmin.Models;
using BlazorAdmin.Web.Shared.Components;
using BlazorAdmin.Web.Shared.Extensions;
using BlazorAdmin.Web.Shared.Services;
using BootstrapBlazor.Components;
using Longbow.Tasks;
using Microsoft.AspNetCore.Components;
using Pangeo.Admin.Tasks;

namespace Pangeo.Admin.Web.Shared.Pages
{
    /// <summary>
    /// Tasks.razor 页面代码
    /// </summary>
    public partial class Tasks
    {
        [Inject]
        private SystemTask taskService {  get; set; }

        protected override void OnInitialized()
        {
            base.OnInitialized();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        private async Task<QueryData<Job>>? OnQueryAsync(QueryPageOptions options)
        {
            var data = await JobService.Query(new AppQueryOption(options, AppContext?.LoginName));
            data.Items = await taskService.CheckSystemTask(data.Items.ToList());

            return data;
        }

        /// <summary>
        /// 保存
        /// </summary>
        private async Task<bool> OnSaveAsync(Job item, ItemChangedType type)
        {
            item.Status = SchedulerStatus.Running.ToString();
            item.Updater = AppContext?.LoginName;
            var errMsg = await JobService.Save(item);

            if (string.IsNullOrEmpty(errMsg))
            {
                await taskService.CheckSystemTask(new List<Job>() { item }, true);

                return true;
            }
            else
            {
                MsgService?.Show(new()
                {
                    Icon = "fa-solid fa-circle-info",
                    Content = errMsg,
                    Color = Color.Danger
                });

                return false;
            }
        }

        

        private static Color GetResultColor(string result) => result switch
        {
            nameof(TriggerResult.Success) => Color.Success,
            nameof(TriggerResult.Error) => Color.Danger,
            nameof(TriggerResult.Timeout) => Color.Warning,
            nameof(TriggerResult.Cancelled) => Color.Dark,
            _ => Color.Primary
        };

        private static string FormatResult(string result) => result switch
        {
            nameof(TriggerResult.Success) => "成功",
            nameof(TriggerResult.Error) => "失败",
            nameof(TriggerResult.Timeout) => "超时",
            nameof(TriggerResult.Cancelled) => "取消",
            _ => "未知状态"
        };

        private static Color GetStatusColor(string status) => status switch
        {
            nameof(SchedulerStatus.Running) => Color.Success,
            nameof(SchedulerStatus.Ready) => Color.Danger,
            nameof(SchedulerStatus.Disabled) => Color.Danger,
            _ => Color.Primary
        };

        private static string GetStatusIcon(string status) => status switch
        {
            nameof(SchedulerStatus.Running) => "fa-solid fa-play-circle",
            nameof(SchedulerStatus.Ready) => "fa-solid fa-stop-circle",
            nameof(SchedulerStatus.Disabled) => "fa-solid fa-times-circle",
            _ => "未知状态"
        };

        private static string FormatStatus(string status) => status switch
        {
            nameof(SchedulerStatus.Running) => "运行中",
            nameof(SchedulerStatus.Ready) => "已停止",
            nameof(SchedulerStatus.Disabled) => "禁用",
            _ => "未知状态"
        };

        /// <summary>
        /// 删除
        /// </summary>
        private async Task<bool> OnDeleteAsync(IEnumerable<Job> items)
        {
            var isSuccess = await JobService.Delete(items.Select(t => t.ID).ToList());
            if (isSuccess)
            {
                // 循环删除任务
                foreach (var item in items)
                {
                    TaskServicesManager.Remove(item.JobCode);
                }
            }

            return isSuccess;
        }

        private Task OnPause(Job item)
        {
            var task = TaskServicesManager.ToList().FirstOrDefault(i => i.Name == item.JobCode);
            if (task != null)
                task.Status = SchedulerStatus.Ready;

            return Task.CompletedTask;
        }

        private Task OnRun(Job item)
        {
            var task = TaskServicesManager.ToList().FirstOrDefault(i => i.Name == item.JobCode);
            if (task != null)
                task.Status = SchedulerStatus.Running;

            return Task.CompletedTask;
        }

        private async Task OnLog(Job item)
        {
            var taskList = TaskServicesManager.ToList().ToTasksModelList();
            var task = taskList.FirstOrDefault(t => t.Name == item.JobCode);
            if (task == null)
                return;

            await DialogService.Show(new DialogOption()
            {
                Class = "modal-dialog-task",
                Title = $"{item.JobName} - 日志窗口(最新 20 条)",
                Component = BootstrapDynamicComponent.CreateComponent<TaskInfo>(new Dictionary<string, object?>
                {
                    [nameof(TaskInfo.Model)] = task
                })
            });
        }

        private static bool OnCheckTaskStatus(Job item) => item.Status != SchedulerStatus.Disabled.ToString();

        #region Items 字典数据

        #endregion

        #region Inject 注入的服务

        [Inject]
        private BootstrapAppContext? AppContext { get; set; }

        [Inject]
        private DialogService? DialogService { get; set; }

        [Inject]
        private MessageService? MsgService { get; set; }

        [Inject]
        private IJob? JobService { get; set; }

        #endregion
    }
}
